package com.buss.admin.controller;

import java.util.Date;

import org.jweb.core.bean.PageMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.MyBeanUtils;
import org.jweb.core.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.buss.admin.entity.AdminEntity;
import com.buss.admin.entity.AuthRoleEntity;
import com.buss.admin.entity.UserRoleEntity;
import com.buss.admin.service.IRoleService;
import com.buss.admin.service.IUserRoleService;
import com.buss.admin.service.IUserService;
import com.buss.admin.trans.form.UserForm;
import com.buss.common.model.json.EasyUIDataGridResult;
import com.buss.common.model.json.HXResult;
import com.buss.common.util.IDUtils;

@RequestMapping("/admin/user")
@Controller
public class UserController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IUserRoleService userRoleService;

	@RequestMapping("/list")
	@ResponseBody
	public EasyUIDataGridResult getUserList(UserForm userForm) {

		// 分页查询
		CriteriaQuery cq = userForm.getCriteriaQuery();

		int pageNo = Integer.parseInt(userForm.getPage());
		int pageSize = Integer.parseInt(userForm.getRows());

		// 定义返回数据格式
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		PageMode<AdminEntity> pageMode = userService.list4page(cq, pageNo, pageSize);

		// 封装数据
		result.setRows(pageMode.getResult());
		result.setTotal(pageMode.getTotal());

		return result;

	}

	@RequestMapping("/delete")
	@ResponseBody
	public HXResult deleteUser(String ids) {

		try {

			String[] split = ids.split(",");
			for (String id : split) {
				// 删除外键关系
				userService.executeSql("DELETE FROM	hx_user_role WHERE	user_id = ?", id);
				userService.deleteEntityById(AdminEntity.class, id);

			}
			return HXResult.ok("删除数据成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器繁忙，请稍后再试！");

		}
	}

	@RequestMapping("/saveorupdate")
	@ResponseBody
	public HXResult savaOrUpdate(AdminEntity adminEntity, String[] roleIds) {

		/*
		 * 保存数据
		 */
		String id = adminEntity.getId();
		if (id == null) {
			// 插入数据操作
			String stringId = IDUtils.getNumStringId();
			adminEntity.setId(stringId);

			Date date = new Date();

			adminEntity.setCreatetime(date);
			adminEntity.setUpdatetime(date);

			String pwdStr = PasswordUtil.encrypt(adminEntity.getPassword(), PasswordUtil.str,
					PasswordUtil.getStaticSalt());
			adminEntity.setPassword(pwdStr);

			userService.saveOrUpdate(adminEntity);

			// 关联外键关系

			if (roleIds != null) {

				for (String roleId : roleIds) {

					// 外键关系实体类
					UserRoleEntity userRoleEntity = new UserRoleEntity();

					// 添加ID
					String stringId2 = IDUtils.getNumStringId();
					userRoleEntity.setId(stringId2);

					AuthRoleEntity roleEntity = roleService.get(AuthRoleEntity.class, roleId);
					userRoleEntity.setRole(roleEntity);
					userRoleEntity.setUser(adminEntity);

					userRoleService.saveOrUpdate(userRoleEntity);
				}

			}

			return HXResult.ok("添加用户成功！");

		} else {
			// 执行修改操作

			// 删除外键关联关系
			userRoleService.executeSql("DELETE FROM	hx_user_role WHERE	user_id = ?", adminEntity.getId());

		
			Date date = new Date();
			adminEntity.setUpdatetime(date);

			AdminEntity temp = userService.get(AdminEntity.class, adminEntity.getId());
			adminEntity.setPassword(temp.getPassword());
			MyBeanUtils.copyBeanNotNull2Bean(adminEntity, temp);
//			userService.saveOrUpdate(adminEntity);
			userService.saveOrUpdate(temp);

			// 保存外键关联关系

			// 关联外键关系

			if (roleIds != null) {

				for (String roleId : roleIds) {

					UserRoleEntity userRoleEntity = new UserRoleEntity();

					String stringId2 = IDUtils.getNumStringId();

					userRoleEntity.setId(stringId2);

					AuthRoleEntity roleEntity = roleService.get(AuthRoleEntity.class, roleId);
					userRoleEntity.setRole(roleEntity);
					userRoleEntity.setUser(adminEntity);

					userRoleService.saveOrUpdate(userRoleEntity);
				}
			}
			return HXResult.ok("更新数据成功！");
		}

	}

	/*
	 * 角色相关页面跳转
	 */
	@RequestMapping("/{path}")
	public String goPath(@PathVariable String path) {
		System.out.println("path:" + path);
		return "admin/user/" + path;
	}

}
